package com.lxb.msmservice.controller;

import com.lxb.commonutils.R;
import com.lxb.msmservice.service.EduMsmService;
import com.lxb.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 阿里云短信和邮件功能控制层
 *
 * @author xuebin.li
 * @createTime 2022/12/19 20:39
 */

@Api(description = "阿里云短信和邮件功能控制层")
@RestController
@RequestMapping("/eduMsm")
//@CrossOrigin
public class MsmController {

    @Autowired
    private EduMsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机短信,设置过期失效
     *
     * @param phone
     * @return
     */
    @ApiOperation("发送手机短信")
    @GetMapping("/sendMs/{phone}")
    public R sendPhone(@PathVariable("phone") String phone) {

        //1.从redis中获取验证码，如果有则直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNotEmpty(code)) {
            return R.ok();
        }

        //2.如果redis获取不到，进行阿里云发送
        //生成四位随机值，传递阿里云进行发送短信
        code = RandomUtil.getFourBitRandom();

        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //封装发送短信需要的相关信息，调用service发送短信方法
        boolean isSend = msmService.send(param, phone);

        if (isSend) {
            //阿里云短信发送成功，存放验证码到redis中
            //设置有效时长
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }


    /**
     * 发送邮件
     *
     * @param email
     * @return
     */
    @ApiOperation("发送邮件")
    @GetMapping("/sendEmail/{email}")
    public R sendEmail(@PathVariable("email") String email) {

        //1.从redis中获取验证码，如果有则直接返回
        String code = redisTemplate.opsForValue().get(email);
        if (StringUtils.isNotEmpty(code)) {
            return R.ok().message("已经发送验证码，五分钟勿再次获取");
        }

        //2.如果redis获取不到code,则通过邮件发送
        //生成四位随机数
        code = RandomUtil.getFourBitRandom();
        //调用service方法发送邮件
        boolean isEmail = msmService.sendEmail(email, code);

        if (isEmail) {
            redisTemplate.opsForValue().set(email,code,5,TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error();
        }
    }

}
